<template>
    <el-dialog v-model="show" title="纸张采购单编辑" width="48%" align-center @close="handleClose">
        <el-form ref="formRef" :model="form" label-position="left">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="材料小类：" label-width="100px">
                        {{ props.initList.paperTypeName }}
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="申请采购数量：">
                        {{ props.initList.applyPurchaseNumber }}{{ getUnitLabel(props.initList.unit) }}
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="品名规格：" label-width="100px">
                        {{ props.initList.specifications }}
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="需求到货日期：" prop="needArriveDate" :rules="[
                        { required: true, message: '请选择需求到货日期' },
                    ]">
                        <el-date-picker v-model="form.needArriveDate" type="date" placeholder="年-月-日"
                            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>

                <el-col :span="10">
                    <div style="display: flex; align-items: center;">
                        <el-form-item label="计划采购数：" label-width="110px" prop="planPurchaseNumber" :rules="[
                            { required: true, message: '请输入计划采购数' },
                            { type: 'number', message: '必须是整数' },
                        ]">
                            <el-input v-model.number="form.planPurchaseNumber" placeholder="请输入" />
                        </el-form-item>
                        <el-form-item prop="unit" :rules="[
                            { required: true, message: '请选择单位' },
                        ]">
                            <el-select v-model="form.unit" placeholder="单位" style="width: 80px;">
                                <el-option v-for="item in unit_enumeration" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="单张价：" prop="singlePrice" :rules="[
                        { required: true, message: '请输入单张价' },
                        { validator: validateNumber, trigger: 'blur' }
                    ]">
                        <el-input v-model="form.singlePrice" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="采购总金额：">
                        {{ Number(form.planPurchaseNumber) * Number(form.singlePrice) }}元
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="克重：" label-width="110px" prop="weight" :rules="[
                        { required: true, message: '请输入克重' },
                        { type: 'number', message: '必须是整数' },
                    ]">
                        <el-input @blur="tonPriceBlur" placeholder="请输入" v-model.number="form.weight">
                            <template #append>g</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="长：" label-width="30px" prop="length" :rules="[
                        { required: true, message: '请输入长' },
                        { type: 'number', message: '必须是整数' },
                    ]">
                        <el-input @blur="tonPriceBlur" placeholder="请输入" v-model.number="form.length">
                            <template #append>mm</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="宽：" label-width="30px" prop="width" :rules="[
                        { required: true, message: '请输入宽' },
                        { type: 'number', message: '必须是整数' },
                    ]">
                        <el-input @blur="tonPriceBlur" placeholder="请输入" v-model.number="form.width">
                            <template #append>mm</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="吨价：" label-width="65px" prop="tonPrice" :rules="[
                        { required: true, message: '请输入吨价' },
                        { type: 'number', message: '必须是整数' },
                    ]">
                        <el-input @blur="tonPriceBlur" placeholder="请输入" v-model.number="form.tonPrice">
                            <template #append>元/吨</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="供应商：" label-width="110px" prop="supplierId" :rules="[
                        { required: true, message: '请选择供应商' },
                    ]">
                        <el-select v-model="form.supplyId" placeholder="请选择供应商">
                            <el-option v-for="item in props.suppliersList" :key="item.id" :label="item.companyName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-checkbox v-model="prePaymentFlag" label="先付款" />
                </el-col>
                <!-- <el-col :span="10">
                    <el-form-item label="补偿金额：">
                        0.112
                    </el-form-item>
                </el-col> -->
                <el-col :span="24">
                    <el-form-item label="备注：" label-width="110px" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmit(formRef)">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { updatePaperPurchaseOrderApi } from '@/api/sj/purchaseManagement/paperProcurement/index';

const { proxy } = getCurrentInstance() as any;
const props = defineProps(['visible', 'initList', 'suppliersList']);
const emits = defineEmits(['submit', 'close']);

const show = ref(false);

const { unit_enumeration } = toRefs(proxy?.useDict('unit_enumeration'));


watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {
        const today = new Date();
        const futureDate = new Date();
        futureDate.setDate(today.getDate() + 3);
        form.needArriveDate = formatDate(futureDate);

        const [weight, length, width] = parseDimensions(props.initList.specifications);

        form.weight = weight;
        form.length = length;
        form.width = width;
    }
}, { deep: true });

const prePaymentFlag = ref(false);

const formRef = ref();

const validateNumber = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback();
    }
    const regex = /^\d+(\.\d+)?$/; // 允许任意位数的小数
    if (!regex.test(value)) {
        return callback(new Error('请输入有效的数字'));
    }
    callback();
};

interface formType {
    needArriveDate: string
    planPurchaseNumber: number | null
    unit: string
    singlePrice: number | null
    weight: number | null
    length: number | null
    width: number | null
    tonPrice: number | null
    supplyId: string
    remark: string
};

const form = reactive<formType>({
    needArriveDate: '',
    planPurchaseNumber: null,
    unit: '',
    singlePrice: null,
    weight: null,
    length: null,
    width: null,
    tonPrice: null,
    supplyId: '',
    remark: ''
});

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {


            const query = {
                id: props.initList.id,
                prePaymentFlag: prePaymentFlag.value ? 1 : 0,
                ...form
            };

            try {
                const { code } = await updatePaperPurchaseOrderApi(query);

                if (code == 200) {
                    proxy?.$modal.msgSuccess('操作成功');
                    emits('submit', true);

                    handleClose();
                }
            } catch (error) {

            }

            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}



const handleClose = () => {
    formRef.value?.resetFields();
    emits('close');
};

/** 根据吨重计算单价 */
const handleChangeWeight = computed(() => {
    console.log('tonPriceBlur');

    const { weight, length, width, tonPrice } = form;

    if (weight && length && width && tonPrice) {
        return (((weight / 1000000) * (length / 1000) * (width / 1000)) * tonPrice).toFixed(3)
    }
});
const tonPriceBlur = () => {
    const { weight, length, width, tonPrice } = form;
    if (weight && length && width && tonPrice) {
        form.singlePrice = Number(handleChangeWeight.value)
    }
};

const formatDate = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

const parseDimensions = (input: string) => {
    const regex = /(\d+(\.\d+)?)/g;
    const matches = input.match(regex);
    if (matches) {
        return matches.map(Number);
    }
    return [];
};


// 辅助函数获取单位标签
const getUnitLabel = (unitValue: string): string => {
    const unit = unit_enumeration.value?.find((item: any) => item.value === unitValue);
    return unit?.label || '';
};


onMounted(() => {
})
</script>

<style lang="scss" scoped></style>